<template>
  <div class="login" @keydown.enter="handleSubmit">
    <div class="login-wrap">
      <div class="login-img-wrap">
        <img src="@/assets/login/hetong.png" class="login-img" />
      </div>
      <div class="login-title">宜昌城市大脑电梯应急处置平台电梯监察系统</div>
      <div class="login-box">
        <div class="huanying">欢迎使用</div>
        <Form ref="loginForm" :model="form" :rules="rules" class="custom-form">
          <FormItem prop="userName">
            <i-input v-model="form.userName" placeholder="账号/手机号" autocomplete="off">
              <span slot="prepend">
                <img src="@/assets/login/user.png" class="form-img" />
              </span>
            </i-input>
          </FormItem>
          <FormItem prop="password">
            <i-input type="password" v-model="form.password" placeholder="输入密码" autocomplete="off">
              <span slot="prepend">
                <img src="@/assets/login/pwd.png" class="form-img" />
              </span>
            </i-input>
          </FormItem>
          <FormItem prop="codeVal">
            <SecurityCode :value.sync="form.codeVal" :biyiCaptchaKey.sync="biyiCaptchaKey" width="396" ref="securityCode">
            </SecurityCode>
          </FormItem>
          <div class="check-wrap" @click="changeRememberme">
            <div :class="{ check: true, on: form.rememberme }"></div>
            <div>记住我</div>
          </div>
          <FormItem>
            <Button @click="handleSubmit" type="primary" long :loading="isLogining" size="large">
              {{ loginBtnText }}
            </Button>
          </FormItem>
          <div class="operate">
            <div class="operate-l">
              <img src="@/assets/login/help.png" class="operate-img" />
              <div>忘记密码</div>
            </div>
            <!-- <div class="operate-l" @click="goRegister">
              <img src="@/assets/login/zhuce.png" class="operate-img" />
              <div>注册账号</div>
            </div> -->
          </div>
        </Form>
      </div>
    </div>
  </div>
</template>

<script>
import SecurityCode from "@/views/components/SecurityCode.vue"
import store from "@/store/store"

export default {
  name: "login",
  components: {
    SecurityCode
  },
  data () {
    return {
      isLogining: false,
      loginBtnText: "登 录",
      rememberme: null,
      form: {
        userName: "",
        password: "",
        codeVal: "",
        rememberme: false
      },
      rules: {
        userName: [
          {
            required: true,
            message: "账号不能为空",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          }
        ]
      },
      biyiCaptchaKey: ""
    }
  },
  mounted () {
    this.$store.commit("user/logout")
    if (!localStorage["rememberme"]) {
      localStorage["rememberme"] = 0
    }
    this.form.rememberme = !(localStorage["rememberme"] === "0")
  },
  methods: {
    async getUserInfo () {
      await this.$http
        .get(this.$util.baseIP + "/api/system/cscpCurrentUserDetails")
        .then(response => {
          this.$store.commit("user/setUserInfo", response.data)

          if (this.$store.state.user.userInfo.state == 0) {
            this.$router.push("/auth")
          } else {
            this.$router.push("/home")
          }
        })
        .catch()
    },
    goRegister () {
      this.$router.push({ name: "register" })
    },
    changeRememberme () {
      this.form.rememberme = !this.form.rememberme
      if (this.form.rememberme) {
        localStorage["rememberme"] = 1
      } else {
        localStorage["rememberme"] = 0
      }
    },
    handleSubmit () {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.isLogining = true
          let msg = this.$Message.loading({
            content: "正在登录中",
            duration: 0
          })
          var pswd = this.$util.encryptPassword
            ? this.$util.encryptPassword(this.form.password)
            : this.form.password
          var username = this.$util.encryptPassword
            ? this.$util.encryptPassword(this.form.userName)
            : this.form.userName

          const [url, data, config] = [
            `${this.$util.baseIP}/api/system/login`,
            {
              systemId: store.state.systemId,
              username: username,
              password: pswd,
              rememberme: localStorage["rememberme"]
            },
            {
              headers: {
                biyiCaptchaKey: this.biyiCaptchaKey,
                biyiCaptcha: JSON.stringify({
                  code: encodeURIComponent(this.form.codeVal)
                })
              }
            }
          ]
          this.$http
            .post(url, data, config)
            .then(response => {
              console.log(response.data)
              localStorage.token = response.data.token
              msg()
              // if (
              //   this.$route.meta.validatePaswd &&
              //   response.data.passwordStatus
              // ) {
              //   this.isLogining = false;
              //   this.$Message.warning({
              //     content:
              //       response.data.passwordStatus === 1
              //         ? "初始密码强度较弱，请修改后再重新登录！"
              //         : "密码已使用3个月，请修改后再重新登录！"
              //   });
              //   this.$byStoreSet("user-info", this.form);
              //   this.$router.push({ name: "update-password" });
              // } else {
              // localStorage.token = response.data.token
              this.$Message.success({
                content: "登录成功！",
                onClose: () => {
                  // console.log(localStorage.userInfo);
                  // this.$router.push('/home')
                  this.getUserInfo()
                }
              })
              // }
            })
            .catch(error => {
              msg()
              this.$refs.securityCode.init()
              this.isLogining = false
              if (error.response) {
                switch (error.response.status) {
                  case 401:
                    console.log(error.response)
                    this.$Message.error(
                      `登录失败，${error.response.data.msg}！`
                    )
                    // if (error.response.data.attempts) {
                    //   this.$Message.error(
                    //     `登录失败，您还有 ${error.response.data.attempts} 尝试机会！`
                    //   );
                    // } else {
                    //   const locktime = this.formatLockedTime(
                    //     error.response.data.lockoutTime
                    //   );
                    //   this.$Message.error({
                    //     content: `登录失败，您的账号已被锁定，请在<span style="font-weight: bold; color: #2d8cf0;">${locktime}</span>后重试！`
                    //   });
                    // }
                    break
                  default:
                    this.$Message.error(
                      `登录失败，${error.response.data.message}！`
                    )
                    break
                }
              }
            })
        }
      })
    },
    formatLockedTime (time) {
      let str = ""
      const d = parseInt(time / (3600 * 24))
      let h = parseInt((time % (3600 * 24)) / 3600)
      let m = parseInt((time % 3600) / 60)
      let s = (time % 3600) % 60
      if (d > 0) {
        str = `${str}${d}天`
      }
      if (h > 0) {
        str = `${str}${h}小时`
      }
      if (m > 0) {
        str = `${str}${m}分`
      }
      if (s > 0) {
        str = `${str}${s}秒`
      }
      return str
    }
  }
};
</script>

<style lang="less" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 100%;
  height: 100%;
  background-position: center;
  background-image: url("../../../assets/login/bg.png");
  background-size: cover;
  .login-wrap {
    width: 560px;
    .login-img-wrap {
      text-align: center;
      .login-img {
        width: 100px;
      }
    }
    .login-title {
      font-size: 38px;
      color: #fff;
      text-align: center;
    }
    .login-box {
      width: 560px;
      // height: 400px;
      margin: 40px 0 0 0;
      padding: 25px 80px;
      background: rgba(255, 255, 255, 0.8);
      box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.1);
      border-radius: 20px;
      .huanying {
        position: relative;
        padding: 0 0 3px 0;
        color: #3a7def;
        font-size: 20px;
        font-weight: 600;
        text-align: center;
        &::before {
          content: "";
          position: absolute;
          bottom: 0;
          left: 50%;
          width: 50px;
          height: 2px;
          background-color: #3a7def;
          transform: translateX(-50%);
        }
      }
      .form-img {
        width: 24px;
      }
      .check-wrap {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin: 0 0 10px 0;
        color: #000;
        font-size: 16px;
        cursor: pointer;
        user-select: text;
        .check {
          position: relative;
          width: 24px;
          height: 24px;
          margin-right: 20px;
          border: 1px solid #0c85ff;
          border-radius: 50%;
          &::before {
            content: "";
            display: block;
            position: absolute;
            top: 50%;
            left: 50%;
            width: 12px;
            height: 12px;
            background-color: transparent;
            border-radius: 50%;
            transform: translate(-50%, -50%);
            z-index: 100;
          }
          &.on {
            &::before {
              content: "";
              display: block;
              position: absolute;
              top: 50%;
              left: 50%;
              width: 12px;
              height: 12px;
              background-color: #0c85ff;
              border-radius: 50%;
              transform: translate(-50%, -50%);
              z-index: 100;
            }
          }
        }
      }
      .operate {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #3a7def;
        font-size: 16px;
        .operate-l {
          display: flex;
          align-items: center;
          cursor: pointer;
          .operate-img {
            width: 24px;
            margin-right: 8px;
          }
        }
      }
    }
  }
}
</style>
<style lang="less">
.custom-form {
  margin: 40px 0 0 0;
  .ivu-form-item-content {
    line-height: 44px;
    .ivu-input {
      height: 44px;
      border: 1px solid #d2d2d2;
      background-color: #fff;
      color: #000;
      font-size: 16px;
    }
  }
}
</style>
